package br.ufc.great.dtx.tm;

import br.ufc.great.dtx.dm.DataManager;
import br.ufc.great.dtx.server.DTXOutput;
import br.ufc.great.dtx.server.DTXServerThread;
import br.ufc.great.dtx.tm.sch.Scheduler;

/**
 * 
 * @author Leonardo Oliveira Moreira
 *
 * Classe quem implementa o gerenciador de transação
 */
public class TransactionManager {

	private Scheduler scheduler;
	private DTXOutput output;
	
	public TransactionManager(DTXOutput output, DataManager dataManager) {
		this.output = output;
		scheduler = new Scheduler(output, dataManager);
		scheduler.start();
	}
	
	public void execute(Transaction transaction, DTXServerThread request) {
		synchronized (this) {
			beginTransaction(transaction, request);			
		}
	}
	
	public void beginTransaction(Transaction transaction, DTXServerThread request) {
		//output.print(getClass().getSimpleName(), "Transaction " + transaction.getId() + " started", DTXOutput.MESSAGE);
		TransactionManagerThread thread = new TransactionManagerThread(output, this, transaction, request);
		thread.start();		
	}
	
	public void endTransaction(Transaction transaction, DTXServerThread request) {
		//output.print(getClass().getSimpleName(), "Transaction " + transaction.getId() + " ended", DTXOutput.MESSAGE);
		request.end();
		System.gc();
	}
	
	public Scheduler getScheduler() {
		return scheduler;
	}
	
	public void end() {
		scheduler.end();
	}
	
	public boolean isRunning() {
		return scheduler.isRunning();
	}
	
}
